package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"sens-fix/cache"
	"sens-fix/model"
	"strconv"
	"time"
)

func CarContractList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT
		  car_contracts.id AS Tid,
		  car_contracts.tract_code AS TractCode,
		  car_contracts.tract_name AS TractName,
		  car_cons.car_on AS CarON,
		  car_cons.car_name AS CarName,
		  car_cons.car_code AS CarCode
		FROM
		  car_contracts
		  LEFT JOIN car_cons ON car_cons.id = car_contracts.cid
	*/
	var list []model.CarContractList
	redis_key := "car_tract_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_contracts").
			Select(
				"car_contracts.id AS Tid",
				"car_contracts.tract_code AS TractCode",
				"car_contracts.tract_name AS TractName",
				"car_cons.car_on AS CarON",
				"car_cons.car_name AS CarName",
				"car_cons.car_code AS CarCode",
			).
			Joins("LEFT JOIN car_cons ON car_cons.id = car_contracts.cid").
			Offset(offset).Limit(size).Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return
}

func CarContractDetail(c *gin.Context) {
	id := c.Query("id")
	var detail model.CarContractList
	redis_key := "car_tract_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_contracts").
			Select(
				"car_contracts.id AS Tid",
				"car_contracts.tract_code AS TractCode",
				"car_contracts.tract_name AS TractName",
				"car_cons.car_on AS CarON",
				"car_cons.car_name AS CarName",
				"car_cons.car_code AS CarCode",
			).
			Joins("LEFT JOIN car_cons ON car_cons.id = car_contracts.cid").
			Where("car_contracts.id = ?", id).Debug().Find(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": detail,
	})
	return
}
